package com.system

import groovy.transform.CompileStatic
import org.springframework.security.authentication.AuthenticationServiceException
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter

import javax.servlet.http.Cookie
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @Author Lee
 * @Description 登录安全验证码
 * @Date 2018年05月27日 21:14
 *
 */
@CompileStatic
class AuthFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        boolean flag = false

        String code = request.getParameter("verifyCode")?.toLowerCase()

        Cookie[] cookies = request.getCookies()
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("verifyCode")) {
                if(cookie.getValue().equals(code)) {
                    flag = true
//                    cookie.setValue(null)
                    cookie.setPath("/")
                    cookie.setDomain("127.0.0.1")
                    cookie.setMaxAge(0)// 立即销毁cookie
                    response.addCookie(cookie)
                    break
                }
            }
        }

        if(flag==false){
            throw new AuthenticationServiceException(this.messages.getMessage("LoginAuthentication.captchaInvalid"))
        }
        return super.attemptAuthentication(request, response)
    }
}
